import mongoose from 'mongoose';
import { Team, ITeamDocument } from '../models/team';

/**
 * 团队数据访问对象
 * 提供团队相关的数据库操作方法
 */
export class TeamDAO {
  /**
   * 创建新团队
   * @param teamData 团队数据
   * @returns 创建的团队文档
   */
  async create(teamData: Partial<ITeamDocument>): Promise<ITeamDocument> {
    try {
      const team = new Team(teamData);
      return await team.save();
    } catch (error: any) {
      if (error.code === 11000) {
        // 处理唯一性约束错误
        const field = Object.keys(error.keyPattern)[0];
        throw new Error(`${field} already exists`);
      }
      throw error;
    }
  }

  /**
   * 根据ID查找团队
   * @param id 团队ID
   * @returns 团队文档或null
   */
  async findById(id: mongoose.Types.ObjectId | string): Promise<ITeamDocument | null> {
    try {
      if (!mongoose.Types.ObjectId.isValid(id)) {
        throw new Error('Invalid team ID format');
      }
      return await Team.findById(id).exec();
    } catch (error) {
      throw error;
    }
  }

  /**
   * 更新团队信息
   * @param id 团队ID
   * @param updateData 更新数据
   * @returns 更新后的团队文档或null
   */
  async update(
    id: mongoose.Types.ObjectId | string,
    updateData: Partial<ITeamDocument>
  ): Promise<ITeamDocument | null> {
    try {
      if (!mongoose.Types.ObjectId.isValid(id)) {
        throw new Error('Invalid team ID format');
      }

      const updatedTeam = await Team.findByIdAndUpdate(
        id,
        updateData,
        { new: true, runValidators: true }
      ).exec();

      return updatedTeam;
    } catch (error: any) {
      if (error.code === 11000) {
        // 处理唯一性约束错误
        const field = Object.keys(error.keyPattern)[0];
        throw new Error(`${field} already exists`);
      }
      throw error;
    }
  }

  /**
   * 删除团队
   * @param id 团队ID
   * @returns 是否删除成功
   */
  async delete(id: mongoose.Types.ObjectId | string): Promise<boolean> {
    try {
      if (!mongoose.Types.ObjectId.isValid(id)) {
        throw new Error('Invalid team ID format');
      }

      const result = await Team.findByIdAndDelete(id).exec();
      return result !== null;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 查找所有团队
   * @param criteria 查询条件
   * @param options 查询选项
   * @returns 团队文档数组
   */
  async findAll(
    criteria: {
      status?: number;
      leaderId?: mongoose.Types.ObjectId | string;
    } = {},
    options: {
      page?: number;
      limit?: number;
      sort?: string;
      select?: string;
    } = {}
  ): Promise<ITeamDocument[]> {
    try {
      const {
        page = 1,
        limit = 10,
        sort = '-createdAt',
        select = ''
      } = options;

      const query: any = {};
      
      // 构建查询条件
      if (criteria.status !== undefined) {
        query.status = criteria.status;
      }
      
      if (criteria.leaderId) {
        query.leaderId = criteria.leaderId;
      }

      let queryBuilder = Team.find(query);
      
      // 应用选择字段
      if (select) {
        queryBuilder = queryBuilder.select(select);
      }
      
      // 应用排序
      queryBuilder = queryBuilder.sort(sort);
      
      // 应用分页
      if (page && limit) {
        const skip = (page - 1) * limit;
        queryBuilder = queryBuilder.skip(skip).limit(limit);
      }

      return await queryBuilder.exec();
    } catch (error) {
      throw error;
    }
  }

  /**
   * 根据团队名称查找团队
   * @param name 团队名称
   * @returns 团队文档或null
   */
  async findByName(name: string): Promise<ITeamDocument | null> {
    try {
      return await Team.findByName(name);
    } catch (error) {
      throw error;
    }
  }

  /**
   * 根据负责人ID查找团队
   * @param leaderId 负责人ID
   * @returns 团队文档数组
   */
  async findByLeader(leaderId: mongoose.Types.ObjectId): Promise<ITeamDocument[]> {
    try {
      return await Team.findByLeader(leaderId);
    } catch (error) {
      throw error;
    }
  }

  /**
   * 根据状态查找团队
   * @param status 状态值
   * @returns 团队文档数组
   */
  async findByStatus(status: number): Promise<ITeamDocument[]> {
    try {
      return await Team.findByStatus(status);
    } catch (error) {
      throw error;
    }
  }
}